﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using MyLib;
using System.Web;

using Portal.Entity;
using Portal.Interface;
using System.Data;

namespace Portal.Logic
{
    /// <summary>
    /// 权限管理
    /// </summary>
    public class SecurityLogic
    {
        /// <summary>
        /// 查询部门Id
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public string GetDepartment(string loginName)
        {
            //定义用户对象获取值
            UserEntity ety = new UserEntity();
            Ultimus.OC.OrgChart oc = new Ultimus.OC.OrgChart();
            Ultimus.OC.User user = new Ultimus.OC.User();
            oc.FindUser(loginName.Replace("\\", "/"), "", 0, out user);

            //获取部门
            Ultimus.OC.Department[] depts;
            user.GetUserDepartments(out depts);
            string DepartId = "";
            if (depts.Length == 0 || depts == null)
            {
                DepartId = "0";
            }
            else
            {
                DepartId = depts[0].strDepartmentID;
            }
            return DepartId;
        }

        /// <summary>
        /// 查询组名
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public List<string> GetGroupName(string loginName)
        {
            //定义用户对象获取值
            UserEntity ety = new UserEntity();
            Ultimus.OC.OrgChart oc = new Ultimus.OC.OrgChart();
            Ultimus.OC.User user = new Ultimus.OC.User();
            oc.FindUser(loginName.Replace("\\", "/"), "", 0, out user);

            //获取组
            Ultimus.OC.Group[] group;
            user.GetUserGroups(out group);
            List<string> lis = new List<string>();
            for (int i = 0; i < group.Length; i++)
            {
                lis.Add(group[i].strGroupName.ToString().Trim());
            }
            return lis;
        }

        /// <summary>
        /// 获取当前用户有权限的资源
        /// </summary>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public List<ResourceEntity> GetSecurityList(string loginName)
        {

            List<ResourceEntity> results = new List<ResourceEntity>();
            ResourceLogic res = new ResourceLogic();
            List<ResourceEntity> list = res.GetResourceList();
            if (ConfigurationManager.AppSettings["AdminAccount"].ToUpper().Contains(loginName.ToUpper())) //超级管理员，不判断权限
            {
                return list.FindAll(p => p.TYPE == "Menu");
            }
            results = list.FindAll(p => p.TYPE == "Menu" && p.EXT06 == "1"); //Ext06=1的菜单，不判断权限
            IOrg org = ServiceContainer.Instance().GetService<IOrg>();
            UserEntity user = org.GetUserEntity(loginName);
            //List<ResourceRelationEntity> relations = DataAccess.Instance("BizDB").GetList<ResourceRelationEntity>("SecurityLogic_GetSecurityList", userid);
            //foreach (ResourceRelationEntity relation in relations)
            //{
            //    if (!results.Exists(p => p.RESOURCEID == relation.DESTINATIONID))
            //    {
            //        results.Add(list.Find(p => p.RESOURCEID == relation.DESTINATIONID));
            //    }
            //}

            //根据用户Id添加权限
            StringBuilder sbUser = new StringBuilder();
            sbUser.AppendFormat(@"select * from com_resource c inner join (select b.ext02 from com_resourcerelation b where b.ext01='USER' and b.destinationid={0}) d
on c.resourceid=d.ext02", user.UserId);
            //modify by ding
            DataTable dd = DataAccess.Instance("BizDB").ExecuteDataTable(sbUser.ToString());
            ReflectUtil ru = new ReflectUtil();
            List<ResourceEntity> relations = new List<ResourceEntity>();
            foreach (DataRow dr in dd.Rows)
            {
                ResourceEntity ety=ru.Build<ResourceEntity>(dd.Columns, dr);
                relations.Add(ety);
            }
            //List<ResourceEntity> relations = DataAccess.Instance("BizDB").GetList<ResourceEntity>(sbUser.ToString());
            if (relations.Count > 0)
            {
                foreach (ResourceEntity relation in relations)
                {
                    if (!results.Exists(p => p.RESOURCEID == relation.RESOURCEID))
                    {
                        results.Add(list.Find(p => p.RESOURCEID == relation.RESOURCEID));
                    }
                }
            }

            //根据部门添加权限
            string DeptId = GetDepartment(loginName);
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat(@"SELECT v.DepartmentID FROM V_DEPARTMENT v START WITH v.DepartmentID='{0}'
CONNECT BY PRIOR v.ParentID=DepartmentID", DeptId);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(sb.ToString());
            List<ResourceEntity> DeptList = new List<ResourceEntity>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {

                string deptid = dt.Rows[i]["DepartmentID"].ToString();
                StringBuilder sbDept = new StringBuilder();
                sbDept.AppendFormat(@"select * from com_resource c inner join (select b.ext02 from com_resourcerelation b where b.ext01='DEPT' and b.destinationid={0}) d
on c.resourceid=d.ext02", deptid);
                //modify by ding
                DataTable d2 = DataAccess.Instance("BizDB").ExecuteDataTable(sbDept.ToString());
                ResourceEntity re = new ResourceEntity();
                if (d2.Rows.Count > 0)
                {
                    re = ru.Build<ResourceEntity>(d2.Columns, d2.Rows[0]);
                }

                //ResourceEntity re = DataAccess.Instance("BizDB").GetEntity<ResourceEntity>(sbDept.ToString());
                if (re != null)
                {
                    DeptList.Add(re);
                }

            }
            if (DeptList.Count > 0)
            {
                foreach (ResourceEntity relation in DeptList)
                {
                    if (!results.Exists(p => p.RESOURCEID == relation.RESOURCEID))
                    {
                        results.Add(list.Find(p => p.RESOURCEID == relation.RESOURCEID));
                    }
                }
            }

            //根据组添加权限
            List<string> group = GetGroupName(loginName);
            List<ResourceEntity> GroupList = new List<ResourceEntity>();
            for (int i = 0; i < group.Count; i++)
            {
                string grp = group[i].Trim().ToString();
                StringBuilder sbGrup = new StringBuilder();
                sbGrup.AppendFormat(@"select * from com_resource c inner join (select b.ext02 from com_resourcerelation b inner join sys_groups s on b.destinationid=s.id where s.groupname='{0}') d
on c.resourceid=d.ext02", grp);

                //modify by ding
                DataTable d3 = DataAccess.Instance("BizDB").ExecuteDataTable(sbGrup.ToString());
                ResourceEntity re = new ResourceEntity();
                if (d3.Rows.Count > 0)
                {
                    re = ru.Build<ResourceEntity>(d3.Columns, d3.Rows[0]);
                }

                //ResourceEntity re = DataAccess.Instance("BizDB").GetEntity<ResourceEntity>(sbGrup.ToString());
                if (re != null)
                {
                    GroupList.Add(re);
                }
            }
            if (GroupList.Count > 0)
            {
                foreach (ResourceEntity relation in GroupList)
                {
                    if (!results.Exists(p => p.RESOURCEID == relation.RESOURCEID))
                    {
                        results.Add(list.Find(p => p.RESOURCEID == relation.RESOURCEID));
                    }
                }
            }

            //移除重复项
            return results;
        }

        /// <summary>
        /// 根据菜单和用户，查找数据权限
        /// </summary>
        /// <param name="menuId"></param>
        /// <param name="loginName"></param>
        /// <returns></returns>
        public List<ResourceEntity> GetSecurityList(int menuId, string loginName)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 根据菜单、类型和用户，查找数据权限
        /// </summary>
        /// <param name="menuId"></param>
        /// <param name="loginName"></param>
        /// <param name="securityType"></param>
        /// <returns></returns>
        public List<ResourceEntity> GetSecurityList(int menuId, string loginName, string securityType)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 获取数据权限类型
        /// </summary>
        /// <returns></returns>
        public List<string> GetSecurityTypeList()
        {
            List<string> strs = new List<string>();
            string[] sz = ConfigurationManager.AppSettings["SecurityType"].Split(',');
            foreach (string str in sz)
            {
                strs.Add(str);
            }
            return strs;
        }

        public int SaveSecurity(int resouceId, string name, string strMembers, string strMemberId, List<SecurityMemberEntity> members, string securityType, List<ResourceEntity> objects)
        {
            ResourceRelationLogic relation = new ResourceRelationLogic();
            SerialNoLogic sn = new SerialNoLogic();

            if (resouceId == 0)
            {
                resouceId = sn.GetSerialNo("COM_Resource");
            }

            ResourceRelationEntity relationEty = new ResourceRelationEntity();
            relationEty.SOURCEID = resouceId;
            relationEty.ID = sn.GetSerialNo("COM_ResourceRelation");

            //查询主菜单Id
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat(@"select * from com_resource r where r.cnname='{0}' and r.type='Menu'", name);
            DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(sb.ToString());

            string type = "";
            string EtyId = "";
            string[] ss = strMemberId.Split('|');
            //判断是resourceid还是角色id
            if (ss.Length > 1)
            {
                //角色id
                string[] rEty = ss[0].ToString().Split('/');
                //判断是否为人
                type = ss[1];
                if (rEty.Length > 1)
                {
                    EtyId = rEty[1];
                }
                else
                {
                    EtyId = rEty[0];
                }

            }
            else
            {
                StringBuilder rsb = new StringBuilder();
                rsb.AppendFormat(@"select * from com_resourcerelation a where a.ext03='{0}' and a.destinationid='{1}' ", strMembers, strMemberId);
                DataTable rdt = DataAccess.Instance("BizDB").ExecuteDataTable(rsb.ToString());
                type = rdt.Rows[0]["ext01"].ToString();
                EtyId = strMemberId;
            }

            if (type == "USER")
            {
                relationEty.DESTINATIONID = Convert.ToInt32(EtyId);
            }

            if (type == "DEPT")
            {
                relationEty.DESTINATIONID = Convert.ToInt32(EtyId);
            }

            if (type == "GROP")
            {
                relationEty.DESTINATIONID = Convert.ToInt32(EtyId);
            }

            relationEty.EXT01 = type;
            relationEty.EXT02 = dt.Rows[0]["resourceid"].ToString().Trim();
            relationEty.EXT03 = strMembers;
            relationEty.RELATIONTYPE = "SecurityMember";

            //保存前删除数据
            string str = "delete com_resourcerelation c where c.ext02=" + relationEty.EXT02 + " and c.destinationid=" + relationEty.DESTINATIONID;
            DataAccess.Instance("BizDB").ExecuteNonQuery(str);

            relation.Save(relationEty);


            //int count = DataAccess.Instance("BizDB").GetEntity<int>("SELECT COUNT(1) FROM COM_RESOURCE WHERE RESOURCEID="+resouceId);
            //ResourceEntity ety = new ResourceEntity();
            //ety.CNNAME = name;
            //ety.ENNAME = name;
            //查询页面路径和父ID
            //StringBuilder sb = new StringBuilder();
            //sb.AppendFormat(@"select t.ext01,t.parentid from COM_RESOURCE t where t.type='Menu' and t.cnname='{0}'", name);
            //DataTable dt = DataAccess.Instance("BizDB").ExecuteDataTable(sb.ToString());
            //ety.EXT01 = dt.Rows[0]["ext01"].ToString();
            //ety.PARENTID = Convert.ToInt32(dt.Rows[0]["parentid"].ToString());
            //ety.RESOURCEID=resouceId;

            //ety.EXT07 = strMembers;
            //ety.EXT08 = ss[0].ToString();
            //ety.TYPE = "Security";
            //ety.ISACTIVE = "1";
            //保存权限名称
            //if (count > 0)
            //{
            //    DataAccess.Instance("BizDB").Update("ResourceLogic_Update", ety);
            //}
            //else
            //{
            //    //生成orderid
            //    DataTable dtOrder = DataAccess.Instance("BizDB").ExecuteDataTable("select max(c.orderno) from com_resource c");
            //    ety.ORDERNO = Convert.ToInt32(dtOrder.Rows[0][0]) + 1;
            //    DataAccess.Instance("BizDB").Insert("ResourceLogic_Insert", ety);
            //}

            //Hashtable table = new Hashtable();
            //table.Add("SourceId", resouceId);
            //table.Add("SecurityType", securityType);
            //DataAccess.Instance("BizDB").Delete("ResourceRelationLogic_Delete", table);
            //保存授权成员
            //foreach (SecurityMemberEntity member in members)
            //{
            //relationEty.DESTINATIONID = member.MemberId;

            //relationEty.EXT01 = member.MemberType;
            //查询MenuId
            //string str = "select t.resourceid from COM_RESOURCE t where t.cnname='"+ety.CNNAME+"'  and t.type='Menu'";
            //DataTable dts = DataAccess.Instance("BizDB").ExecuteDataTable(str);
            //}
            //保存授权对象
            //foreach (ResourceEntity resource in objects)
            //{
            //    ResourceRelationEntity relationEty = new ResourceRelationEntity();
            //    relationEty.SOURCEID = resouceId;
            //    relationEty.ID = sn.GetSerialNo("COM_ResourceRelation");
            //    //relationEty.DESTINATIONID = resource.RESOURCEID;
            //    string[] rEty = ss[0].ToString().Split('/');
            //    relationEty.DESTINATIONID = Convert.ToInt32(rEty[1]);
            //    relationEty.EXT01 = resource.TYPE;
            //    relationEty.RELATIONTYPE = "SecurityObject";
            //    relation.Save(relationEty);
            //}
             
            return resouceId;
        }


    }
}
